﻿using HalconDotNet;
using Halcon二次开发.Controller.Controller基类;
using Halcon二次开发.Controller.卡尺;
using Halcon二次开发.Controller.多模板匹配;
using Halcon二次开发.Controller.模板匹配;
using Halcon二次开发.Controller.画线工具交互;
using Halcon二次开发.Model;
using Halcon二次开发.Model.储存每个Controller的单例对象;
using Halcon二次开发.Model.储放所有单例.储存每个单例界面;
using Halcon二次开发.Model.帮助类.VHelper;
using Halcon二次开发.Model.自定义控件;
using Halcon二次开发.Tools;
using Halcon二次开发.View.OCR字符识别;
using Halcon二次开发.View.Socket通信;
using Halcon二次开发.View.九点标定;
using Halcon二次开发.View.卡尺;
using Halcon二次开发.View.多文本显示工具;
using Halcon二次开发.View.多模板匹配;
using Halcon二次开发.View.定位跟随;
using Halcon二次开发.View.找圆_线_矩形;
using Halcon二次开发.View.文本显示工具;
using Halcon二次开发.View.模板匹配;
using Halcon二次开发.View.相机;
using Halcon二次开发.View.结果分析工具;
using Halcon二次开发.View.膨胀与腐蚀;
using Halcon二次开发.View.距离转换工具;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Halcon二次开发.Controller.主界面交互
{
    public class Form1Controller : ControllerBase
    {
        public override void Run() { }
        //每个对象的工程文件的路径
        public string filePath= $@"..\..\Data\工程文件\";
        /// <summary>
        /// 用来判断
        /// </summary>
        public string name;
        private bool isMoving = false;
        private Point startPoint;
        //List<Form> forms = new List<Form>();
        int camerIndex, cirleIndex,lineIndex,shapIndex, PreciseCaliperIndex,FixtrueIndex, nodecirleIndex, distanceIndex
            , messageTextIndex, swellEtchIndex,arcIndex,ninePointIndex,pmasIndex,showTextsIndex,analyseIndex, OCRIndex,socketIndex;

        TreeView la1;
        /// <summary>
        /// 鼠标双击事件
        /// </summary>
        public void Btn_Double_Click(HwindowFlowNodeUrseControl hwindow, object tree) 
        {
            //获取当前板块的所有小工具窗体,工具窗体
            bool check = false;            
            la1 = tree as TreeView;
            if (la1.SelectedNode == null) return;
            string str = la1.SelectedNode.Text;
            Form form = null;
            bool camerCheck = true;
            foreach (TreeNode item in hwindow.treeView1.Nodes)
            {
                if (item.Text.Contains("相机工具"))
                {
                    camerCheck = false;
                }
            }
            if (la1.SelectedNode.Text == "相机工具")
            {
                if (camerCheck)
                {
                    str += 0;
                    form = new CamerForm();
                    AddHeadNode(form, str, hwindow, la1.SelectedNode.ImageIndex);
                }

            }
            else if (la1.SelectedNode.Text == "找线工具")
            {
                str += lineIndex;
                form = new H_FindLineToolForm();
                AddHeadNode(form, str, hwindow, la1.SelectedNode.ImageIndex);
            }
            else if (la1.SelectedNode.Text == "找圆工具")
            {
                str += cirleIndex;
                form = new H_FindCirleToolForm();
                AddHeadNode(form, str, hwindow, la1.SelectedNode.ImageIndex);
            }
            else if (la1.SelectedNode.Text.Contains("精准测量"))
            {
                str += PreciseCaliperIndex;
                form = new PreciseCaliper();
                AddHeadNode(form, str, hwindow, la1.SelectedNode.ImageIndex);
            }
            else if (la1.SelectedNode.Text.Contains("距离转换工具"))
            {
                str += distanceIndex;
                form = new DistanceToolForm();
                AddHeadNode(form, str, hwindow, la1.SelectedNode.ImageIndex);
            }
            else if (la1.SelectedNode.Text.Contains("九点标定"))
            {
                str += ninePointIndex;
                form = new NinePointCalibrationForm();
                AddHeadNode(form, str, hwindow, la1.SelectedNode.ImageIndex);
            }
            else if (la1.SelectedNode.Text.Contains("多目标模型匹配"))
            {
                str += pmasIndex;
                form = new H_PMA_S_AlignToolForm();
                (form as H_PMA_S_AlignToolForm).SetPathNodes(filePath + StaicResouce.HwindowFlowNodeUrse.name + "工程文件", str);
                AddHeadNode(form, str, hwindow, la1.SelectedNode.ImageIndex);
            }
            else if (la1.SelectedNode.Text.Contains("多文本工具"))
            {
                str += showTextsIndex;
                form = new MessageBoxStringsForms();
                AddHeadNode(form,str,hwindow, la1.SelectedNode.ImageIndex);
            }
            else if (la1.SelectedNode.Text.Contains("测量分析工具"))
            {
                str += analyseIndex;
                form = new AnalyseResultForms();
                AddHeadNode(form, str, hwindow, la1.SelectedNode.ImageIndex);
            }else if (la1.SelectedNode.Text.Contains("socket通讯"))
            {
                str += socketIndex;
                form = new SocketChildForm();
                AddHeadNode(form, str, hwindow, la1.SelectedNode.ImageIndex);
            }
        }
        public void AddHeadNode(Form form,string name, HwindowFlowNodeUrseControl hwindow,int imageIndex)
        {
            form.Name = name;
            form.Text = name;
            TreeNode treeNode = new TreeNode(name);
            treeNode.Name = name;
            treeNode.Text = form.Name;
            ContextMenuStrip contex = new ContextMenuStrip();
            //增加一个事件
            contex.Items.Add("删除节点", Image.FromFile("..\\..\\Data\\Image\\Exit2.png"));
            contex.Items[0].Click += Form1Controller_Click;
            contex.Items[0].Tag = treeNode;
            treeNode.ContextMenuStrip = contex;
            treeNode.Tag = form;
            form.Tag = treeNode;
            //添加输出子节点
            foreach (var item in form.GetType().GetFields())
            {
                if (item.Name == "controller")
                {
                    object controllerObj = item.GetValue(form);
                    foreach ( var item1  in controllerObj.GetType().GetFields())
                    {
                        ContextMenuStrip contex1 = new ContextMenuStrip();
                        TreeNode childNode = null;
                        bool paper = false;
                        if (item1.Name.Contains("Int") && !item1.Name.Contains("Hide"))
                        {
                            childNode = new TreeNode(item1.Name);
                            childNode.ImageIndex = 75;
                            paper = true;
                            //添加右击菜单 以及 菜单的子菜单
                            AddChildMenuStrip(childNode);
                        }
                        else if (item1.Name.Contains("Out") && !item1.Name.Contains("Hide"))
                        {
                            childNode = new TreeNode(item1.Name);
                            childNode.ImageIndex = 155;
                            paper = true;
                        }
                        else if (item1.Name.Contains("IntOrOut") && !item1.Name.Contains("Hide"))
                        {
                            childNode = new TreeNode(item1.Name);
                            childNode.ImageIndex = 156;
                            paper = true;

                            AddChildMenuStrip(childNode);
                        }
                        if (paper && childNode != null)
                        {
                            childNode.Name = item1.Name;
                            childNode.Tag = controllerObj;
                            treeNode.Nodes.Add(childNode);
                            //针对PMA进行特殊处理  (以后有基准数据时在这里扩展)
                            if (form is H_PMAAlignToolForm)
                            {
                                //将我们存储的数据给到ShapMatching
                                string paths = filePath + StaicResouce.HwindowFlowNodeUrse.name + "工程文件" + "\\" + "基准数据" + "\\" + name + "基准数据" + "\\" + "standar.txt";
                                //判断文件中有没有这个基准数据文件
                                if (File.Exists(paths))
                                {
                                    //单模板匹配赋值，基准数据赋值
                                    if (treeNode.Nodes[0].Tag is ShapMatching)
                                    {
                                        ShapMatching s = (ShapMatching)treeNode.Nodes[0].Tag;
                                        List<double> values = HelpJsons.Read<double>(paths);
                                        s.OutStandardRow = values[0];
                                        s.OutStandardColumn = values[1];
                                    }
                                }
                            }
                            //多模板匹配的基准数据加载
                            else if (form is H_PMA_S_AlignToolForm)
                            {
                                //将我们存储的数据给到Shap_S_Matching
                                string paths = filePath + StaicResouce.HwindowFlowNodeUrse.name + "工程文件" + "\\" + "基准数据" + "\\" + name + "基准数据" + "\\" + "standar.txt";
                                //判断文件中有没有这个基准数据文件
                                if (File.Exists(paths))
                                {
                                    //多模板基准数据
                                    if (treeNode.Nodes[0].Tag is Shap_S_Matching)
                                    {
                                        Shap_S_Matching s = (Shap_S_Matching)treeNode.Nodes[0].Tag;
                                        List<double> values = HelpJsons.Read<double>(paths);
                                        s.HideOutputStandardRow = values[0];
                                        s.HideOutputStandardColumn = values[1];
                                    }
                                }
                            }
                        }
                    }
                }
            }
            treeNode.ImageIndex = imageIndex;
            //添加节点
            hwindow.treeView1.Nodes.Add(treeNode);
            //同步工具计数器  
            string index = name[name.Length - 1].ToString();//获取节点最后一个字符 
            if (form is CamerForm)
            {

                camerIndex = int.Parse(index);
                camerIndex++;
            }
            else if (form is H_FindLineToolForm)
            {
                lineIndex = int.Parse(index);
                lineIndex++;
            }
            else if (form is H_FindCirleToolForm)
            {
                cirleIndex = int.Parse(index);
                cirleIndex++;
            }
            else if (form is H_PMAAlignToolForm)
            {
                shapIndex = int.Parse(index);
                shapIndex++;
            }
            else if (form is PreciseCaliper)
            {
                PreciseCaliperIndex = int.Parse(index);
                PreciseCaliperIndex++;
            }
            else if (form is FixtureToolFForm)
            {
                FixtrueIndex = int.Parse(index);
                FixtrueIndex++;
            }
            else if (form is DistanceToolForm)
            {
                distanceIndex = int.Parse(index);
                distanceIndex++;
            }
            else if (form is MessageBoxTextForm)
            {
                messageTextIndex = int.Parse(index);
                messageTextIndex++;
            }
            else if (form is SwellEtchToolFrom)
            {
                swellEtchIndex = int.Parse(index);
                swellEtchIndex++;
            }
            else if (form is NinePointCalibrationForm)
            {
                ninePointIndex = int.Parse(index);
                ninePointIndex++;
            } else if (form is H_PMA_S_AlignToolForm) {
                pmasIndex = int.Parse(index);
                pmasIndex++;
            }
            else if (form is OCRForm)
            {
                OCRIndex = int.Parse(index);
                OCRIndex++;
            }
            else if (form is AnalyseResultForms)
            {
                analyseIndex=int.Parse(index);
                analyseIndex++;
            }else if (form is SocketChildForm)
            {
                socketIndex = int.Parse(index);
                socketIndex++;
            }else if(form is MessageBoxStringsForms)
            {
                showTextsIndex = int.Parse(index);
                showTextsIndex++;
            }
        }
        /// <summary>
        /// 初始化右击菜单栏
        /// </summary>
        /// <param name="childNode"></param>
        public void AddChildMenuStrip(TreeNode childNode)
        {
            ContextMenuStrip context = new ContextMenuStrip();
            ToolStripMenuItem toolStrip1 = new ToolStripMenuItem("连接至");
            ToolStripMenuItem toolStrip2 = new ToolStripMenuItem("取消连接");
            context.Items.Add(toolStrip1);
            context.Items.Add(toolStrip2);
            context.Items[1].Tag = childNode;
            childNode.ContextMenuStrip = context;
            toolStrip2.Click += ToolStrip2_Click;
        }
        /// <summary>
        /// Int/IntOrOut 取消连接操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ToolStrip2_Click(object sender, EventArgs e)
        {
             object obj= (sender as ToolStripMenuItem).Tag;
            if (obj != null)
            {
                TreeNode node=(sender as ToolStripMenuItem).Tag as TreeNode;
                string str = node.Text.Substring(0,node.Text.IndexOf('<'));
                //获取这个实例
                object form = node.Parent.Tag.GetType().GetField("controller").GetValue(node.Parent.Tag);
                //获取这个字段对象
                FieldInfo value = node.Parent.Tag.GetType().GetField("controller").GetValue(node.Parent.Tag).GetType().GetField(str);
                
                if (value.GetType().IsPrimitive)
                {
                    //基本数据类型
                    value.SetValue(form, 0);
                }
                else {
                    string xx = form.GetType().Name;
                    //对象类型
                    value.SetValue(form, null );   
                }
                if (node.Text != node.Name)
                {
                    node.Text = node.Name;
                    node.ForeColor = Color.Black;
                }else
                {
                    return;
                }

            }
        }
        /// <summary>
        /// 删除节点事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1Controller_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem x = (ToolStripMenuItem)sender;
            TreeNode node =  (TreeNode)x.Tag;
            foreach (var item in StaicResouce.HomeForms)
            {
                HwindowFlowNodeUrseControl sss =  item as HwindowFlowNodeUrseControl;
                if (sss.name==name)
                {
                    TreeView treeView = sss.treeView1;
                    //清理使用此节点输出端的子节点
                    int index= treeView.Nodes.IndexOf(node);
                    for (int i = index; i < treeView.Nodes.Count; i++)// 循环根节点
                    {
                        //释放socket工具的输入段子
                        // node.Text （核心） 删除的节点文本
                        if (treeView.Nodes[i].Tag is SocketChildForm)
                        {
                            TreeView view= (treeView.Nodes[i].Tag as SocketChildForm).treeView1;
                            foreach (TreeNode childNode in view.Nodes[0].Nodes)
                            {
                                if (childNode.Text.Contains(node.Text.Trim()))
                                {
                                    childNode.ForeColor = Color.Black;
                                    childNode.Text = childNode.Name;
                                }
                            }
                            continue;
                        }

                        TreeNodeCollection childNodes = treeView.Nodes[i].Nodes;
                        foreach (TreeNode childNode in childNodes)// 循环子节点
                        {
                           string[] childNodeText= childNode.Text.Split(new char[] { '<', '—' },StringSplitOptions.RemoveEmptyEntries);
                            if (childNodeText.Length > 1)
                            {
                                string str=  childNodeText[1].Split('.')[0];
                                if (str == node.Text)
                                {
                                    childNode.Text = childNode.Name;
                                    childNode.ForeColor = Color.Black;
                                }
                            }
                        }
                        
                    }
                    //释放绘制的区域
                    if (node.Nodes.Count != 0)
                    {
                        object obj = node.Nodes[0].Tag;
                        if (obj is ShapMatching)
                        {
                            (obj as ShapMatching).ClearTwoObject( StaicResouce.HwindowFlowNodeUrse.hSmartWindowControl1.HalconWindow);
                        }
                        else if (obj is FindCrileToolController || obj is FindLineToolController || obj is Caliper)
                        {
                            MethodInfo method= obj.GetType().GetMethod("ClearObject");
                            method.Invoke(obj,null);
                        }
                    }

                    //释放窗体
                    if (node.Tag is Form)
                    {
                        //释放非静态的
                        (node.Tag as Form).Close();
                        (node.Tag as Form).Dispose();
                    }
                    //彻底删除该节点
                    treeView.Nodes.Remove(node);

                    //释放节点占有的文件
                }
            }
        }
        /// <summary>`
        /// 打开窗体
        /// </summary>
        /// <param name="sender"></param>
        public void ShowForm(object obj) {
            if (obj != null && obj is Form)
            {
                (obj as Form).Show();
            }
        }
    }
}
